using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.WebUtilities;
using SumerCoreDevOps.ExecuteNodeApi.Services;

namespace SumerCoreDevOps.ExecuteNodeApi.Controllers;

/// <summary>
/// 节点注册控制器 - 提供 HTTP 接口用于一键注册
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class RegistrationController : ControllerBase
{
    private readonly ILogger<RegistrationController> _logger;
    private readonly NodeRegistrationService _registrationService;
    private readonly HotRegistrationService _hotRegistrationService;
    private readonly IConfiguration _configuration;

    public RegistrationController(
        ILogger<RegistrationController> logger,
        NodeRegistrationService registrationService,
        HotRegistrationService hotRegistrationService,
        IConfiguration configuration)
    {
        _logger = logger;
        _registrationService = registrationService;
        _hotRegistrationService = hotRegistrationService;
        _configuration = configuration;
    }

    /// <summary>
    /// 一键注册页面 - 用户访问此页面即可完成节点注册
    /// GET /api/registration/register?url=http://192.168.1.59:5000?token=abc&name=a
    /// 兼容旧版: GET /api/registration/register?master=http://control-panel:5136&token=abc123
    /// </summary>
    [HttpGet("register")]
    public async Task<IActionResult> Register(
        [FromQuery] string? url,
        [FromQuery] string? master,
        [FromQuery] string? token,
        [FromQuery] string? name)
    {
        try
        {
            // 如果提供了 url 参数,从中解析所有参数
            if (!string.IsNullOrEmpty(url))
            {
                try
                {
                    var uri = new Uri(url);

                    // 提取基础 URL (scheme + host + port + path)
                    master = $"{uri.Scheme}://{uri.Authority}{uri.AbsolutePath}";

                    // 解析查询参数
                    var queryParams = QueryHelpers.ParseQuery(uri.Query);

                    // 从 URL 中提取 token 和 name (如果存在)
                    if (queryParams.TryGetValue("token", out var tokenValue))
                    {
                        token = tokenValue.ToString();
                    }

                    if (queryParams.TryGetValue("name", out var nameValue))
                    {
                        name = nameValue.ToString();
                    }

                    _logger.LogInformation("从 URL 参数解析: Master={Master}, Token={Token}, Name={Name}",
                        master, token ?? "(无)", name ?? "(自动检测)");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "解析 URL 参数失败: {Url}", url);
                    return BadRequest(new
                    {
                        success = false,
                        message = "URL 参数格式错误,无法解析",
                        error = ex.Message
                    });
                }
            }

            if (string.IsNullOrEmpty(master))
            {
                return BadRequest(new
                {
                    success = false,
                    message = "缺少必需参数: url 或 master (主节点 HTTP URL)"
                });
            }

            _logger.LogInformation("收到注册请求: Master={Master}, Token={Token}, Name={Name}",
                master, token ?? "(无)", name ?? "(自动检测)");

            // 执行热注册
            _logger.LogInformation("开始执行热注册...");
            var result = await _hotRegistrationService.HotRegisterAsync(master, token, name);

            if (result.Success)
            {
                // 注册成功
                var html = GenerateSuccessHtml(master, result.NodeId, result.NodeName, result.MasterId);
                return Content(html, "text/html");
            }
            else
            {
                // 注册失败
                var html = GenerateFailureHtml(master, token, name, result.ErrorMessage);
                return Content(html, "text/html");
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "注册请求处理失败");
            return StatusCode(500, new
            {
                success = false,
                message = "注册请求处理失败",
                error = ex.Message
            });
        }
    }

    /// <summary>
    /// 生成成功页面HTML
    /// </summary>
    private string GenerateSuccessHtml(string masterUrl, long nodeId, string nodeName, string masterId)
    {
        return $@"
<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <title>注册成功 - SumerCore DevOps</title>
    <style>
        body {{
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            max-width: 800px;
            margin: 50px auto;
            padding: 20px;
            background: #f5f5f5;
        }}
        .container {{
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }}
        h1 {{
            color: #2c3e50;
            border-bottom: 3px solid #4caf50;
            padding-bottom: 10px;
        }}
        .success {{
            background: #e8f5e9;
            border-left: 4px solid #4caf50;
            padding: 15px;
            margin: 20px 0;
        }}
        .info {{
            background: #e3f2fd;
            border-left: 4px solid #2196f3;
            padding: 15px;
            margin: 20px 0;
        }}
        .detail {{
            margin: 10px 0;
            padding: 10px;
            background: #fafafa;
            border-radius: 4px;
        }}
        .detail strong {{
            color: #3498db;
        }}
    </style>
</head>
<body>
    <div class='container'>
        <h1>🎉 注册成功!</h1>

        <div class='success'>
            <strong>✅ 节点已成功注册并连接到主节点</strong>
        </div>

        <div class='info'>
            <strong>📋 节点信息:</strong>
            <div class='detail'>
                <strong>节点ID:</strong> {nodeId}
            </div>
            <div class='detail'>
                <strong>节点名称:</strong> {nodeName}
            </div>
            <div class='detail'>
                <strong>主节点地址:</strong> {masterUrl}
            </div>
            <div class='detail'>
                <strong>连接到:</strong> {masterId}
            </div>
        </div>

        <div class='info' style='margin-top: 30px;'>
            <strong>📌 提示:</strong>
            <ul>
                <li>节点已成功连接到主节点,无需重启服务</li>
                <li>节点配置已保存,下次启动将自动重连</li>
                <li>现在可以在主节点的管理界面中查看此节点</li>
            </ul>
        </div>
    </div>
</body>
</html>
";
    }

    /// <summary>
    /// 生成失败页面HTML
    /// </summary>
    private string GenerateFailureHtml(string masterUrl, string? token, string? nodeName, string errorMessage)
    {
        var command = $"dotnet run -- --discovery-url={masterUrl}";

        if (!string.IsNullOrEmpty(token))
        {
            command += $" --join-token={token}";
        }

        if (!string.IsNullOrEmpty(nodeName))
        {
            command += $" --node-name={nodeName}";
        }

        return $@"
<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <title>注册失败 - SumerCore DevOps</title>
    <style>
        body {{
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            max-width: 800px;
            margin: 50px auto;
            padding: 20px;
            background: #f5f5f5;
        }}
        .container {{
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }}
        h1 {{
            color: #2c3e50;
            border-bottom: 3px solid #f44336;
            padding-bottom: 10px;
        }}
        .error {{
            background: #ffebee;
            border-left: 4px solid #f44336;
            padding: 15px;
            margin: 20px 0;
        }}
        .warning {{
            background: #fff3e0;
            border-left: 4px solid #ff9800;
            padding: 15px;
            margin: 20px 0;
        }}
        .info {{
            background: #e3f2fd;
            border-left: 4px solid #2196f3;
            padding: 15px;
            margin: 20px 0;
        }}
        .command {{
            background: #263238;
            color: #aed581;
            padding: 15px;
            border-radius: 4px;
            font-family: 'Courier New', monospace;
            overflow-x: auto;
            margin: 10px 0;
        }}
        button {{
            background: #3498db;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            margin-top: 10px;
        }}
        button:hover {{
            background: #2980b9;
        }}
    </style>
</head>
<body>
    <div class='container'>
        <h1>❌ 注册失败</h1>

        <div class='error'>
            <strong>错误详情:</strong><br>
            {errorMessage}
        </div>

        <div class='warning'>
            <strong>⚠️ 配置已回滚</strong><br>
            系统已自动回滚到注册前的配置,服务继续使用原有的主节点连接。
        </div>

        <div class='info'>
            <strong>💡 可能的解决方案:</strong>
            <ul>
                <li>检查主节点地址是否正确: {masterUrl}</li>
                <li>确认主节点服务是否正常运行</li>
                <li>检查网络连接是否正常</li>
                <li>验证 JoinToken 是否正确(如果需要)</li>
                <li>查看服务日志获取更多详细信息</li>
            </ul>
        </div>

        <div class='info'>
            <strong>📌 备用方案 - 手动注册:</strong>
            <p>如果问题持续,您可以重启服务并使用以下命令手动注册:</p>
            <div class='command'>
                <pre id='command'>{command}</pre>
            </div>
            <button onclick='copyCommand()'>📋 复制命令</button>
            <button onclick='retryRegistration()' style='background: #ff9800; margin-left: 10px;'>🔄 重试注册</button>
        </div>
    </div>

    <script>
        function copyCommand() {{
            const command = document.getElementById('command').textContent;
            navigator.clipboard.writeText(command).then(() => {{
                alert('命令已复制到剪贴板!');
            }});
        }}

        function retryRegistration() {{
            window.location.reload();
        }}
    </script>
</body>
</html>
";
    }

    /// <summary>
    /// 获取当前节点状态
    /// </summary>
    [HttpGet("status")]
    public IActionResult GetStatus()
    {
        var isRegistered = _registrationService.NodeId > 0;

        return Ok(new
        {
            success = true,
            registered = isRegistered,
            nodeId = isRegistered ? (long?)_registrationService.NodeId : null,
            message = isRegistered ? "节点已注册" : "节点未注册"
        });
    }
}
